<script setup lang="ts">
import { addTemplateApi, getTemplList, updateTemplateApi } from "@/api/alert";
import CustomTabs from "@/components/Tabs/index.vue";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import { PxMessage } from "px-ui";
import { getCurrentInstance, onMounted, reactive, ref, toRefs, watch } from "vue";

const activeTab = ref("email");
const tabList = ref([
  {
    name: "email",
    label: "邮件"
  },
  {
    name: "center",
    label: "消息通知中心"
  }
]);
const emits = defineEmits(["backMainPage", "handleSubmit"]);
const isMain = defineModel("isMain");
const isEdit = defineModel("isEdit");

const props = defineProps({
  // 主页面/详情页面
  editVal: { type: Object || null, default: null }
});
const mailRightSearch = ref("");
const formRef = ref();
const { proxy }: any = getCurrentInstance();
let searchBackup = {};
let curFormInput = "";
const data = reactive<Record<string, any>>({
  form: {},
  rules: {
    templateName: [{ required: true, message: "请输入报警模板名称", trigger: ["blur", "change"] }],
    pushChannel: [{ required: true, message: "请选择推送渠道", trigger: ["blur", "change"] }],
    // recoverNoticeFlag: [{ required: true, message: "请选择报警恢复后是否发送恢复通知", trigger: ["blur", "change"] }],
    noticeTemplateContent: [{ required: true, message: "请输入报警通知模板内容", trigger: ["blur", "change"] }],
    recoverTemplateContent: [{ required: true, message: "请输入报警恢复模板内容", trigger: ["blur", "change"] }]
  }
});
watch(
  () => isEdit.value,
  async newVal => {
    if (newVal && props.editVal) {
      form.value = JSON.parse(JSON.stringify(props.editVal));
    }
  }
);
watch(
  () => isMain.value,
  async newVal => {
    if (!newVal) {
      searchBackup = await getTemplList();
      templateList.value = deepCopy(searchBackup);
    }
  }
);
const templateList = ref();
const { form, rules } = toRefs(data);
function backMainPage() {
  isMain.value = true;
  reset();
}
function submitForm(formEl) {
  console.log("fordata", form.value);
  handleSubmit(formEl);
}
const handelTabSelected = selectName => {
  activeTab.value = selectName;
};
function searchFun() {
  if (!mailRightSearch.value) {
    templateList.value = searchBackup;
  } else {
    templateList.value = fuzzySearchObj(searchBackup, mailRightSearch.value);
  }
}
/** 表单重置 */
function reset() {
  form.value = {
    alarmLevel: "",
    pushPost: "",
    pushChannel: [],
    pushTemplate: "",
    enableStatus: ""
  };
  proxy.resetForm("formRef");
  isEdit.value = false;
  searchBackup = {};
  templateList.value = {};
  mailRightSearch.value = "";
}
onMounted(async () => {
  searchBackup = await getTemplList();
  templateList.value = deepCopy(searchBackup);
});
function fuzzySearchObj(obj, str) {
  // 创建一个空对象用于存放匹配的结果
  const result = {};

  // 遍历obj中的每一个键值对
  for (const [key, value] of Object.entries(obj)) {
    // 将key和value转换为字符串形式，确保可以进行包含（include）检查
    // 注意：这里假设value是可以转换为字符串的，如果是复杂对象可能需要额外处理
    if (key.includes(str) || value.toString().includes(str)) {
      // 如果key或value包含str，则将这个键值对添加到结果对象中
      result[key] = value;
    }
  }

  // 返回包含匹配结果的新对象
  return result;
}
function deepCopy(raw) {
  try {
    return JSON.parse(JSON.stringify(raw));
  } catch (error) {
    console.log(error);
    return {};
  }
}
function mailRightInsert(val, key) {
  let str = `${val}\{\{${key}\}\}`;
  if (!curFormInput) {
    return;
  }
  if (!form.value[curFormInput]) {
    form.value[curFormInput] = str;
  } else {
    form.value[curFormInput] += str;
  }
}
function secondBlur() {
  console.log("blur");
  curFormInput = null;
}
function curFormInputFun(val) {
  curFormInput = val;
}
const handleSubmit = async formEl => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      if (isEdit.value) {
        await updateTemplateApi(form.value);
        PxMessage.success("修改成功");
      } else {
        await addTemplateApi(form.value);
        PxMessage.success("新增成功");
      }
      emits("handleSubmit");
      backMainPage();
    }
  });
};
</script>

<template>
  <div v-show="!isMain" class="add-config-detail add-config-content">
    <!-- <px-scrollbar class="add-config-content"> -->
    <px-button type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
    <px-scrollbar height="calc(100% -180px)">
      <EditDropDown dropdownTitle="基础信息">
        <template v-slot:content>
          <px-form ref="formRef" style="width: 100%" :model="form" label-width="120px" label-position="right" :rules="rules">
            <px-form-item label="通知模板名称" prop="templateName">
              <px-input v-model="form.templateName" maxlength="50" placeholder="请输入通知模板名称" />
            </px-form-item>
            <!-- <px-form-item label="告警恢复后是否发送恢复通知" prop="recoverNoticeFlag">
            <px-radio-group v-model="form.recoverNoticeFlag">
              <px-radio label="TRUE">是</px-radio>
              <px-radio label="FALSE">否</px-radio>
            </px-radio-group>
          </px-form-item> -->
            <px-form-item label="模板描述">
              <px-input
                v-model="form.templateDesc"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 6 }"
                placeholder="请输入模板描述"
                maxlength="255"
                show-word-limit
              />
            </px-form-item>
          </px-form>
        </template>
      </EditDropDown>
      <EditDropDown dropdownTitle="通知模板">
        <template v-slot:content>
          <div style="width: 100%; margin-top: -12px">
            <CustomTabs :tabList="tabList" :activeName="activeTab" @tabSelect="handelTabSelected" />
            <div v-if="activeTab === 'email'" class="flex">
              <div class="mail-left">
                <div class="card-wrapper mb-[24px]">
                  <div class="card-header">通知模板</div>
                  <px-card shadow="never" class="h-[150px]">
                    <px-form ref="formRefNotice" :model="form" label-width="70px" label-position="right" :rules="rules">
                      <px-form-item label="通知标题" prop="noticeTemplateTitle">
                        <px-input
                          v-model="form.noticeTemplateTitle"
                          maxlength="50"
                          placeholder="请输入"
                          @focus="curFormInputFun('noticeTemplateTitle')"
                        />
                      </px-form-item>
                      <px-form-item label="通知内容">
                        <px-input
                          v-model="form.noticeTemplateContent"
                          type="textarea"
                          :autosize="{ minRows: 2, maxRows: 3 }"
                          placeholder="请输入"
                          maxlength="5000"
                          show-word-limit
                          @focus="curFormInputFun('noticeTemplateContent')"
                        />
                      </px-form-item>
                    </px-form>
                  </px-card>
                </div>
                <div class="card-wrapper">
                  <div class="card-header">恢复模板</div>
                  <px-card shadow="never" class="h-[150px]">
                    <px-form ref="formRefRecover" :model="form" label-width="70px" label-position="right" :rules="rules">
                      <px-form-item label="通知标题" prop="recoverTemplateTitle">
                        <px-input
                          v-model="form.recoverTemplateTitle"
                          maxlength="50"
                          placeholder="请输入"
                          @focus="curFormInputFun('recoverTemplateTitle')"
                        />
                      </px-form-item>
                      <px-form-item label="通知内容">
                        <px-input
                          v-model="form.recoverTemplateContent"
                          type="textarea"
                          :autosize="{ minRows: 2, maxRows: 3 }"
                          placeholder="请输入"
                          maxlength="5000"
                          show-word-limit
                          @focus="curFormInputFun('recoverTemplateContent')"
                        />
                      </px-form-item>
                    </px-form>
                  </px-card>
                </div>
              </div>
              <div class="mail-right">
                <px-input v-model="mailRightSearch" class="w-[100%] mb-[13px]" placeholder="请输入" @change="searchFun">
                  <template #prefix>
                    <px-icon class="px-input__icon">
                      <search />
                    </px-icon>
                  </template>
                </px-input>
                <px-card shadow="never" class="w-[100%]">
                  <px-scrollbar height="290px">
                    <div
                      v-for="(val, key) in templateList"
                      :key="key"
                      style="font-size: 14px"
                      class="flex h-[40px] border-b border-[#DCDCDC] justify-between items-center pl-[16px]"
                    >
                      {{ `${val}\{\{${key}\}\}` }}
                      <px-button type="primary" text @click="mailRightInsert(val, key)">插入</px-button>
                    </div>
                  </px-scrollbar>
                </px-card>
              </div>
            </div>
            <div v-if="activeTab === 'center'">消息通知中心</div>
          </div>
        </template>
      </EditDropDown>
    </px-scrollbar>
    <!-- </px-scrollbar> -->
    <div class="px-dialog-footer">
      <px-button @click="backMainPage">取消</px-button>
      <px-button type="primary" @click="submitForm(formRef)">保存</px-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.add-config-detail {
  width: 100%;
  height: 100%;

  .px-dialog-footer {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 50px;
    padding-top: 10px;
    padding-right: 34px;
    text-align: right;
    background: white;
    box-shadow: 0 0 10px 0 rgb(0 0 0 / 16%);
  }
}

.add-config-content {
  background-color: #fff;
  width: 100%;
  box-sizing: border-box;
  padding: 16px 24px 40px;
  .mail-left {
    width: 76%;
    .card-wrapper {
      display: flex;
      flex-direction: column;

      .card-header {
        margin-bottom: 12px;
        font-size: 14px;
        font-weight: bolder;
        line-height: 22px;
        color: rgb(0 0 0 / 80%);
      }
    }
  }
  .mail-right {
    flex: 1;
    margin-left: 24px;
    display: flex;
    flex-direction: column;
    padding-top: 34px;

    :deep(.px-card__body) {
      padding-top: 0 !important;
      padding-right: 0 !important;
      padding-left: 0 !important;
    }
  }
}
</style>
